package cn.edu.xust.health.controller;

import cn.edu.xust.health.entity.User;
import cn.edu.xust.health.service.TokenService;
import cn.edu.xust.health.service.UserService;
import lombok.extern.java.Log;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@Log
@RestController
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private TokenService tokenService;

    @PutMapping("/user/sign/up")
    public Map<String,Object> signUp(@RequestBody User user) {
        log.info( user.toString() );
        if( userService.exists( user.getEmail() ) ) {
            return Map.of("success",false,"message", "邮箱已经被占用");
        }
        userService.save(user);
        return Map.of("success",true,"message", "注册成功");
    }

    @PostMapping("/user/sign/in")
    public Map<String,Object> signIn(@RequestBody User u) {
        // 由参数传递的 u 对象中所包含的 email 和 password 都是来自前端的
        // 根据前端传递的邮箱从数据库中寻找用户信息
        User udb =userService.find(u.getEmail());
        if(udb == null) {
            return Map.of("success",false,"message", "邮箱在系统中不存在");
        }
        // 使用 encrypt 方法对来自前端的密码进行加密(使用从数据库中获取的盐值)
        String encrypted = userService.encrypt(u.getPassword(), udb.getSalt());
        // 检查前端输入的密码被加密后是否与数据库中密码不一致
        if( !encrypted.equals( udb.getPassword() ) ) {
            return Map.of("success",false,"message", "登录密码错误");
        }
        // 使用 Service 中的方法生成 JSON Web Token
        String jwt = tokenService.produce(udb);
        return Map.of("success",true,"message", "登录成功", "token", jwt);
    }

    @GetMapping("/user/list")
    public List<User> list() {
        log.info("list");
        List<User> users = userService.findAll();
        users.forEach(System.out::println);
        return users;
    }

    @DeleteMapping("/user/remove/{id}")
    public Map<String,Object> remove(@PathVariable("id") Long id) {
        log.info("remove user " + id );
        userService.remove(id);
        return Map.of("success", true, "message", "删除成功");
    }

    @PostMapping("/user/update")
    public Map<String, Object> update(@RequestBody User user) {
        userService.update(user);
        return Map.of("success", true, "message", "修改成功");
    }

    @GetMapping("/user/find/{id}")
    public User find(@PathVariable("id") Long id) {
        return userService.find(id);
    }

}
